/*
Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.
*/


class Solution {
public:
    bool canJump(int A[], int n) {
        if (n<=1) return true;
        int reach = 0;
        for (int i = 0; i < n-1; i++) {
            reach = max(reach, i+A[i]);
            if (i >= reach) return false; // stuck
        }
        return true; // proceeds to (n-1)
    }
};

/* dynamic programming */
class Solution {
public:
    bool canJump(int A[], int n) {
        if (n<=1) return true;
        int f = A[0];
        for (int i = 1; i < n; i++) {
            f = max(f, A[i-1])-1;
            if (f < 0) return false;
        }
        return true;
    }
};

#if 0
class Solution {
public:
    bool canJump(int A[], int n) {
        if (n <= 1) return true;
        int idx = findZero(A, n);
        if (idx < 0) return true;
        // determine if zero can be hit or bypassed
        for (int i = idx-1; i >= 0; i--) {
            if ((idx == n-1 && A[i] >= idx-i) || (A[i] > idx-i)) {
                return canJump(A, i+1);
            }
        }
        return false;
    }
private:
    int findZero(int A[], int n) {
        while (--n >=0) {if (A[n] == 0) break;}
        return n;
    }
};
#endif
